#!/bin/bash
# Analyze User Plane PCAP Files
# Converts and analyzes N1, N3, and N6 interface captures

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CAPTURES_DIR="../docs/5gc-interfaces/captures/user-plane"
OUTPUT_DIR="./analysis/user-plane"

echo "=== 5GC User Plane Analysis ==="
echo "Script directory: $SCRIPT_DIR"
echo "Captures directory: $CAPTURES_DIR"
echo "Output directory: $OUTPUT_DIR"
echo

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Function to analyze a PCAP file
analyze_pcap() {
    local input_file="$1"
    local output_file="$2"
    local description="$3"
    
    if [[ -f "$input_file" ]]; then
        echo "Analyzing $description..."
        echo "  Input: $input_file"
        echo "  Output: $output_file"
        
        # Convert to JSON with summary
        python3 "$SCRIPT_DIR/pcap-to-json.py" "$input_file" "$output_file" --summary
        
        echo "  ✓ Completed"
        echo
    else
        echo "⚠ Skipping $description - file not found: $input_file"
        echo
    fi
}

# Analyze N1 interface (UE ↔ gNodeB)
analyze_pcap \
    "$CAPTURES_DIR/n1_interface_vm1.pcap" \
    "$OUTPUT_DIR/n1_ue_gnb_analysis.json" \
    "N1 Interface (UE ↔ gNodeB)"

# Analyze N3 interface (gNodeB ↔ UPF)
analyze_pcap \
    "$CAPTURES_DIR/n3_gnb_user_plane.pcap" \
    "$OUTPUT_DIR/n3_gnb_upf_analysis.json" \
    "N3 Interface (gNodeB ↔ UPF)"

# Analyze N3 interface (alternative capture)
analyze_pcap \
    "$CAPTURES_DIR/n3_user_plane.pcap" \
    "$OUTPUT_DIR/n3_user_plane_analysis.json" \
    "N3 Interface (User Plane)"

# Analyze N6 interface (UPF ↔ Internet)
analyze_pcap \
    "$CAPTURES_DIR/n6_internet.pcap" \
    "$OUTPUT_DIR/n6_internet_analysis.json" \
    "N6 Interface (UPF ↔ Internet)"

# Generate summary report
echo "=== Generating Summary Report ==="
cat > "$OUTPUT_DIR/summary_report.txt" << EOF
5GC User Plane Analysis Summary
===============================
Generated: $(date)
Script: $0

Files Analyzed:
EOF

# Check which files were processed
for file in n1_interface_vm1.pcap n3_gnb_user_plane.pcap n3_user_plane.pcap n6_internet.pcap; do
    if [[ -f "$CAPTURES_DIR/$file" ]]; then
        echo "✓ $file" >> "$OUTPUT_DIR/summary_report.txt"
    else
        echo "✗ $file (not found)" >> "$OUTPUT_DIR/summary_report.txt"
    fi
done

cat >> "$OUTPUT_DIR/summary_report.txt" << EOF

Output Files:
- n1_ue_gnb_analysis.json: N1 interface analysis (UE ↔ gNodeB)
- n3_gnb_upf_analysis.json: N3 interface analysis (gNodeB ↔ UPF)
- n3_user_plane_analysis.json: N3 interface analysis (User Plane)
- n6_internet_analysis.json: N6 interface analysis (UPF ↔ Internet)

Analysis Results:
EOF

# Add analysis results if files exist
for analysis_file in n1_ue_gnb_analysis.json n3_gnb_upf_analysis.json n3_user_plane_analysis.json n6_internet_analysis.json; do
    if [[ -f "$OUTPUT_DIR/$analysis_file" ]]; then
        echo "" >> "$OUTPUT_DIR/summary_report.txt"
        echo "=== $analysis_file ===" >> "$OUTPUT_DIR/summary_report.txt"
        python3 -c "
import json
try:
    with open('$OUTPUT_DIR/$analysis_file', 'r') as f:
        data = json.load(f)
    print(f'Total packets: {data[\"metadata\"][\"total_packets\"]}')
    print(f'Protocols: {list(data[\"statistics\"][\"protocols\"].keys())}')
    print(f'Top source IPs: {list(data[\"statistics\"][\"source_ips\"].keys())[:3]}')
    print(f'Top dest IPs: {list(data[\"statistics\"][\"dest_ips\"].keys())[:3]}')
    
    # Calculate total data volume if size information is available
    total_size = 0
    for packet in data['packets']:
        if packet.get('size'):
            total_size += packet['size']
    if total_size > 0:
        print(f'Total data volume: {total_size} bytes ({total_size/1024:.2f} KB)')
        
except Exception as e:
    print(f'Error reading file: {e}')
" >> "$OUTPUT_DIR/summary_report.txt"
    fi
done

echo "Summary report generated: $OUTPUT_DIR/summary_report.txt"
echo
echo "=== Analysis Complete ==="
echo "Results saved in: $OUTPUT_DIR"
echo
echo "To view detailed analysis:"
echo "  cat $OUTPUT_DIR/summary_report.txt"
echo "  jq '.' $OUTPUT_DIR/*.json"
echo
echo "To analyze data flow patterns:"
echo "  python3 $SCRIPT_DIR/analyze-data-flow.py $OUTPUT_DIR" 